package com.briup.labs.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符，apache校验下载的文件的正确性用的就是默认的这个组合
     * */
    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    protected static MessageDigest messageDigest = null;

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException nsaex) {
            System.err.println(Md5Util.class.getName() + "初始化失败，MessageDigest不支持MD5Util.");
            nsaex.printStackTrace();
        }
    }

    /**
     * 生成字符串的md5校验值
     *
     * @param s
     * @return
     */
    public static String getMD5String(String s) {
        return getMD5String(s.getBytes());
    }

    /**
     * 生成字节数组的md5校验值
     *
     * @param bytes 字节数组
     * @return MD5校验值
     */
    public static String getMD5String(byte[] bytes) {
        messageDigest.update(bytes);
        byte[] digest = messageDigest.digest();
        return bufferToHex(digest);
    }

    private static String bufferToHex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder(2 * bytes.length);
        for (byte b : bytes) {
            stringBuilder.append(hexDigits[(b >> 4) & 0x0f]);
            stringBuilder.append(hexDigits[b & 0x0f]);
        }
        return stringBuilder.toString();
    }
}
